/**
 * 
 */
package com.manyi.ihouse.schedue;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.manyi.ihouse.model.CompareMo;
import com.manyi.ihouse.util.CompareListUtils;
import com.manyi.ihouse.util.DateUtil;
import com.manyi.ihouse.util.HttpsUtil;
import com.manyi.ihouse.util.SendMailUtil;

@Component
public class GetLianjiaWebInfo {
    //    private static final Logger logger = Logger.getLogger(GetLianjiaWebInfo.class);

    private static String path = "/usr/share/software/userappBatchSever/data/searchLianjia/";

    //    private static String path = "D:/data/";

    @Scheduled(cron="0 0 10,12,14,16,18 * * ?")
    public void getLianjiaWebInfo() {
        System.out.println("GetLianjiaWebInfo start");
        String[] cityname = { "上海", "深圳", "北京", "南京", "天津" };
        String[] url = { "http://sh.fang.lianjia.com", "http://sz.fang.lianjia.com",
                "http://bj.fang.lianjia.com", "http://nj.fang.lianjia.com",
                "http://tj.fang.lianjia.com" };
        //        String[] urlH5 = {"http://m.lianjia.com/sh/xinfang",
        //                        "http://m.lianjia.com/sz/xinfang",
        //                        "http://m.lianjia.com/bj/xinfang",
        //                        "http://m.lianjia.com/nj/xinfang",
        //                        "http://m.lianjia.com/tj/xinfang"};
        String[] urlApp = {
                "https://soa.dooioo.com/api/v4/online/homepage/city/function?cityCode=sh&client=ios&version=210",
                "https://app.api.lianjia.com/newhouse/appindex?city_id=440300&request_ts=1477880613",
                "https://app.api.lianjia.com/newhouse/appindex?city_id=110000&request_ts=1477880701",
                "https://app.api.lianjia.com/newhouse/appindex?city_id=320100&request_ts=1477880757",
                "https://app.api.lianjia.com/newhouse/appindex?city_id=120000&request_ts=1477880779" };
        String space = "&nbsp;&nbsp;&nbsp;&nbsp;";

        StringBuilder content = new StringBuilder();
        content.append("hi：");
        content.append("<br>" + space);
        content.append("以下是五个城市的新房开放状态：");
        content.append("<br>" + space);
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();
        File propertiesFile = new File(dir.getAbsolutePath(), "/lastDayInfo.properties");
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(propertiesFile));
        } catch (IOException e) {
            System.err.println("load properties error. " + e.getMessage());
        }
        StringBuilder change = new StringBuilder();
        for (int i = 0; i < url.length; i++) {
            int pcStatus = 0;
            //            int h5Status = 0;
            int appStatus = 0;
            int oldStatus = 0;
            try {
                oldStatus = Integer.parseInt(properties.getProperty(cityname[i]));
            } catch (Exception e) {
            }
            content.append(cityname[i] + "：");
            // pc
            boolean checkPc = false;
            if (i == 0) {
                checkPc = checkPcShUrl(url[i]);
            } else {
                checkPc = checkPcUrl(url[i]);
            }
            if (checkPc) {
                content.append("<a href='" + url[i] + "'>PC开放</a>");
                pcStatus = 1;
            } else {
                content.append("<a href='" + url[i] + "'>PC关闭</a>");
            }
            // H5的M站
            //            try {
            //                Document doc = Jsoup.connect(urlH5[i]).get();
            //                Elements el = doc.select("div[class=content_area] input");
            //                if(el.size()>0) {
            //                    content.append(space+"<a href='"+ urlH5[i] +"'>"+"H5的M站开放</a>");
            //                    h5Status = 10;
            //                } else {
            //                    content.append(space+"<a href='"+ urlH5[i] +"'>"+"H5的M站关闭</a>");
            //                }
            //            } catch(Exception e) {
            //                logger.error("GetLianjiaWebInfo H5 error",e);
            //                content.append(space+"<a href='"+ urlH5[i] +"'>"+"H5的M站关闭</a>");
            //            }

            // App
            try {
                int check = 0;
                if (i == 0) {
                    check = checkAppForSh(urlApp[i]);
                } else {
                    check = checkAppForNotSh(urlApp[i]);
                }
                if (check == 1) {
                    content.append(space + "App开放");
                    appStatus = 100;
                } else {
                    content.append(space + "App关闭");
                }
            } catch (Exception e) {
                System.err.println("checkApp error. " + e.getMessage());
                content.append(space + "App无法查询");
            }

            if (oldStatus % 10 != pcStatus
            //                    || oldStatus/10%10 != h5Status/10%10
                || oldStatus / 100 % 10 != appStatus / 100 % 10) {
                change.append(cityname[i] + "：");
                if (oldStatus % 10 != pcStatus) {
                    change.append("PC&nbsp;&nbsp;").append(oldStatus % 10 == 1 ? "开放" : "关闭")
                        .append(" ==> ").append(pcStatus == 1 ? "开放" : "关闭").append(space);
                }
                //                if(oldStatus/10%10 != h5Status/10%10) {
                //                    change.append("H5的M站&nbsp;&nbsp;").append(oldStatus/10%10 == 1?"开放":"关闭")
                //                    .append(" ==> ").append(h5Status/10%10 == 1?"开放":"关闭").append(space);
                //                }
                if (oldStatus / 100 % 10 != appStatus / 100 % 10) {
                    change.append("App&nbsp;&nbsp;")
                        .append(oldStatus / 100 % 10 == 1 ? "开放" : "关闭").append(" ==> ")
                        .append(appStatus / 100 % 10 == 1 ? "开放" : "关闭").append(space);
                }
                change.append("<br>" + space);
            }

            properties.put(cityname[i], String.valueOf(pcStatus
            //                +h5Status
                                                       + appStatus));
            content.append("<br>" + space);
        }
        // 刷新内容
        try {
            properties
                .store(new FileOutputStream(propertiesFile), DateUtil.date2string(new Date()));
        } catch (IOException e) {
            System.err.println("write properties error. " + e.getMessage());
        }
        content.append("<br>" + space);
        if (change.length() > 0) {
            content.append("城市业务变化情况：").append("<br>").append(space);
            content.append(change.toString());
        } else {
            content.append("各城市无变化");
        }
        System.out.println(content);
        // 发送邮件
        SendMailUtil sendMailUtil = new SendMailUtil("smtp.exmail.qq.com",
            "huangjun.sh@superjia.com", "Hj6986482",
            "huangjun.sh@superjia.com,caihui@superjia.com,hubin@superjia.com", "");
        //            "hekezui.sh@superjia.com", "");
        String subject = "上海  深圳   北京   南京 天津  新房开放情况（" + DateUtil.date2string(new Date()) + "）";
        sendMailUtil.sendMail(subject, content.toString());

        System.out.println("GetLianjiaWebInfo end");
    }

    private int checkAppForSh(String url) {
        if (StringUtils.isBlank(url))
            return -1;
        String result = HttpsUtil.getShHttps(url);
        JSONObject json = JSONObject.fromObject(result);
        if (json != null) {
            JSONArray array = json.getJSONArray("functions");
            if (array != null && array.size() > 0) {
                for (int i = 0; i < array.size(); i++) {
                    if (array.get(i) == null)
                        continue;
                    JSONObject tmpJson = array.getJSONObject(i);
                    String functionName = tmpJson.getString("functionName");
                    if (functionName != null && "新房".equals(functionName.trim())) {
                        return 1;
                    }
                }
                return 0;
            }
        }
        return -1;
    }

    private int checkAppForNotSh(String url) {
        if (StringUtils.isBlank(url))
            return -1;
        String result;
        try {
            result = HttpsUtil.getHttpReturn(url);
            JSONObject json = JSONObject.fromObject(result);
            if (json != null) {
                JSONObject data = json.getJSONObject("data");
                if (data == null)
                    return 0;
                JSONObject hot_build = data.getJSONObject("hot_build");
                if (hot_build == null)
                    return 0;
                JSONArray array = hot_build.getJSONArray("list");
                if (array != null && array.size() > 0) {
                    System.out.println(url + "----------->" + array.size());
                    return 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public boolean checkPcUrl(String url) {
        boolean result = false;
        // 测试
        try {
            String docXmlStr = HttpsUtil.getHttpReturn(url);
            Document doc = Jsoup.parse(docXmlStr);
            Elements el = doc.select("div[class=xinfang-all] div[class=all] i");
            int saleNum = 0;
            if (el.size() > 0) {
                try {
                    saleNum = Integer.parseInt((el.get(0).text()));
                } catch (Exception e) {
                }
                if (saleNum > 0)
                    result = true;
            }
            System.out.println(url + "----------->" + saleNum);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean checkPcShUrl(String url) {
        boolean result = false;
        // 测试
        try {
            String docXmlStr = HttpsUtil.getHttpReturn(url);
            Document doc = Jsoup.parse(docXmlStr);
            Elements el = doc.select("ul[class=house-lst] li");
            int saleNum = 0;
            if (el != null && el.size() > 0) {
                saleNum = el.size();
                result = true;
            }
            System.out.println(url + "----------->" + saleNum);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Test
    public void getLianjiaWebInfoTest() {
        // 测试
        try {
            //          String docXmlStr = HttpsUtil.getHttpReturn("http://sz.fang.lianjia.com/");
            //          Document doc = Jsoup.parse(docXmlStr);
            //          String originalFileStr = path + "originalFile.txt";
            //          File compareFile = new File(path + "compareFile.txt");
            //          compareFile(originalFileStr, compareFile, doc.toString());
            //          Elements el = doc.select("div[class=xinfang-all] div[class=all] i");
            //          if(el.size()>0) {
            //              el.get(0).text();
            System.out.println("H5的M站开放</a>");
            //          } else {
            //              System.out.println("H5的M站关闭</a>");
            //          }
            checkPcShUrl("http://sh.fang.lianjia.com");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件比较
     * @param originalFileStr
     * @param compareFile
     * @param content
     */
    private void compareFile(String originalFileStr, File compareFile, String content) {
        if (compareFile.exists())
            compareFile.delete();
        List<String> original = CompareListUtils.fileToLines(originalFileStr);
        CompareListUtils.linesToFile(originalFileStr, content);
        if (original == null || original.size() == 0)
            return;
        List<String> revised = CompareListUtils.fileToLines(originalFileStr);
        List<CompareMo> compares = CompareListUtils.compareAll(original, revised);
        StringBuilder compareStr = new StringBuilder();
        for (CompareMo compare : compares) {
            if (CompareListUtils.Result_EQUAL.equals(compare.getType()))
                continue;
            compareStr.append(compare.getId() + " 结果:" + compare.getType() + "::"
                              + compare.getOldText() + "  <=====>  "
                              + compare.getNewText() + "\n");
        }
        CompareListUtils.linesToFile(compareFile, compareStr.toString());
    }
    
   
}
